#pragma once
#include <queue>
#include <pthread.h>


template <class T>
class BlockQueue
{
public:
    BlockQueue(int cap) : _cap(cap)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_producer, nullptr);
        pthread_cond_init(&_consumer, nullptr);
    }
    void push(const T& data)
    {
        pthread_mutex_lock(&_mutex);
        while(_q.size() == _cap)
        {
            pthread_cond_wait(&_producer, &_mutex);
        }
        _q.push(data);
        pthread_cond_signal(&_consumer);
        pthread_mutex_unlock(&_mutex);
    }
    T pop()
    {
        pthread_mutex_lock(&_mutex);
        while(_q.empty())
        {
            pthread_cond_wait(&_consumer, &_mutex);
        }
        T ret = _q.front();
        _q.pop();
        pthread_cond_signal(&_producer);
        pthread_mutex_unlock(&_mutex);
        return ret;
    }
    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_producer);
        pthread_cond_destroy(&_consumer);
    }

private:
    std::queue<T> _q;
    int _cap;
    pthread_mutex_t _mutex;
    pthread_cond_t _producer;
    pthread_cond_t _consumer;
};